package com.blen.videolib;

//import com.changba.songstudio.recording.RecordingImplType;
//import com.changba.songstudio.recording.camera.preview.ChangbaRecordingPreviewScheduler;
//import com.changba.songstudio.recording.camera.preview.ChangbaRecordingPreviewView;
//import com.changba.songstudio.recording.camera.preview.ChangbaVideoCamera;
//import com.changba.songstudio.recording.exception.RecordingStudioException;
//import com.changba.songstudio.recording.exception.StartRecordingException;
//import com.changba.songstudio.recording.service.PlayerService;
//import com.changba.songstudio.recording.video.CommonVideoRecordingStudio;
//import com.changba.songstudio.recording.video.VideoRecordingBase;
//import com.changba.songstudio.util.FFmpegUtils;
//import com.blen.videolib.util.FFUtils;
//import com.blen.videolib.util.FileUtils;


public class VideoRecorderActivity extends BaseActivity {
//    private static final boolean isSlotable = false;//是否分段
//    private static final boolean isTakingPhoto = false;//是否可以拍照
//    private static final int CHOOSE_VIDEO = 10003;
//    public static final int REQUEST_KEY = 100;
//
//    //录制视频
//    private static final int HANDLER_RECORD = 200;
//    //编辑视频
//    private static final int HANDLER_EDIT_VIDEO = 201;
//    //拍摄照片
//    private static final int HANDLER_CAMERA_PHOTO = 202;
//
//
//    private TextView tvTimeLabel,tvHint;
//    private ChangbaRecordingPreviewView surfaceView;
//    private RecordedButton rbStart;
//    private ImageView imgBack,imgAlbum;
//
//    private long lastEnterTime = 0;
//    private WakeLock wakeLock = null;
//
//    protected static final int START_RECORD_FAIL = 16271;
//
//
//    private boolean isRecording;
//
//
//    private ChangbaVideoCamera videoCamera;
//    private ChangbaRecordingPreviewScheduler previewScheduler;
//    private CommonVideoRecordingStudio recordingStudio;
//
//    private String path;
//
//    private boolean isUseHWEncoder = true;
//    private long startTime = 0l;
//    private boolean isRecordedOver;
//    private boolean isVideoData;
//
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_video_recorder);
//        preProcess();
//        findView();
//        initRecordingStudio();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//
//        mHandler.removeCallbacksAndMessages(null);
//        previewScheduler.releaseCameraFromNative();
//        videoCamera.releaseCamera();
//    }
//
//    private void initRecordingStudio() {
//        path = FFmpegUtils.getVideoRecordingFilePath();
//        videoCamera = new ChangbaVideoCamera(this);
//        previewScheduler = new ChangbaRecordingPreviewScheduler(surfaceView, videoCamera) {
//            @Override
//            public void onPermissionDismiss(final String tip) {
//                mHandler.post(() -> Toast.makeText(VideoRecorderActivity.this, tip, Toast.LENGTH_SHORT).show());
//            }
//        };
//        recordingStudio = new CommonVideoRecordingStudio(RecordingImplType.ANDROID_PLATFORM,
//                mHandler,
//                () -> { },
//                recordingStudioStateCallback);
//
//    }
//
//    private void startRecord() {
//        try {
//            recordingStudio.initRecordingResource(previewScheduler);
//        } catch (RecordingStudioException e) {
//            recordingStudio.destroyRecordingResource();
//            return;
//        }
//        recordStart();
//    }
//
//    public void recordStart() {
//
//        int adaptiveBitrateWindowSizeInSecs = 3;
//        int adaptiveBitrateEncoderReconfigInterval = 15 * 1000;
//        int adaptiveBitrateWarCntThreshold = 10;
//
//        int height = 1280;
//        int width = 720;
//        int bitRateKbs = 4*1024;
//        int audioSampleRate = recordingStudio.getRecordSampleRate();
//        recordingStudio.startVideoRecording(path,bitRateKbs, width, height,
//                audioSampleRate,0, adaptiveBitrateWindowSizeInSecs, adaptiveBitrateEncoderReconfigInterval,
//                adaptiveBitrateWarCntThreshold,300, 800, isUseHWEncoder);
//        isRecording = true;
//        startTime = System.currentTimeMillis();
//    }
//
//    private VideoRecordingBase.RecordingStudioStateCallback recordingStudioStateCallback = new VideoRecordingBase.RecordingStudioStateCallback() {
//        @Override
//        public void onConnectRTMPServerFailed() {
////            isPublishing = false;
////            mHandler.post(new Runnable() {
////                @Override
////                public void run() {
////                    connect_tip_layout.setVisibility(View.GONE);
////                    rbStart.setText(getResources().getString(R.string.start_live));
////                    rbStart.setVisibility(View.VISIBLE);
//////                    rbStart.setOnClickListener(VideoRecorderActivity.this);
////                    rbStart.setClickable(true);
////                    countDownTimeSec = 3;
////                    initRecordingStudio();
////                    mCompleteBtn.setVisibility(View.GONE);
////                    Toast.makeText(VideoRecorderActivity.this, "连接RTMP服务器失败", Toast.LENGTH_SHORT).show();
////                }
////            });
//        }
//
//        @Override
//        public void onConnectRTMPServerSuccessed() {
////            isPublishing = true;
////            mHandler.post(new Runnable() {
////                @Override
////                public void run() {
////                    connect_tip_layout.setVisibility(View.GONE);
////                }
////            });
//        }
//
//        @Override
//        public void onStartRecordingException(final StartRecordingException exception) {
//            mHandler.post(() -> Toast.makeText(VideoRecorderActivity.this, exception.getMessage(), Toast.LENGTH_SHORT)
//                    .show());
//        }
//
//        @Override
//        public void onPublishTimeOut() {
//
////            mHandler.post(() -> {
////                recordStop();
////                load_text_tip.setText(getResources().getString(R.string.publish_timeout_tip));
////                connect_tip_layout.setVisibility(View.VISIBLE);
////                rbStart.setVisibility(View.VISIBLE);
////                mCompleteBtn.setVisibility(View.GONE);
////                Toast.makeText(VideoRecorderActivity.this, "推流期间，由于网络原因超时", Toast.LENGTH_SHORT).show();
////            });
//        }
//
//        @Override
//        public void statisticsCallback(long startTimeMills, int connectTimeMills, int publishDurationInSec,
//                                       float discardFrameRatio, float publishAVGBitRate, float expectedBitRate, String adaptiveBitrateChart) {
//            StringBuilder statisticsBuilder = new StringBuilder("statisticsCallback : ");
//            statisticsBuilder.append("startTimeMills【").append(startTimeMills).append("】");
//            statisticsBuilder.append("connectTimeMills【").append(connectTimeMills).append("】");
//            statisticsBuilder.append("publishDurationInSec【").append(publishDurationInSec).append("】");
//            statisticsBuilder.append("discardFrameRatio【").append(discardFrameRatio).append("】");
//            statisticsBuilder.append("publishAVGBitRate【").append(publishAVGBitRate).append("】");
//            statisticsBuilder.append("expectedBitRate【").append(expectedBitRate).append("】");
//            statisticsBuilder.append("adaptiveBitrateChart【").append(adaptiveBitrateChart).append("】");
//            Log.i("problem", statisticsBuilder.toString());
//        }
//
//        @Override
//        public void adaptiveVideoQuality(int videoQuality) {
//            boolean invalidFlag = false;
//            boolean showUserTip = false;
//            int bitrate = VideoRecordingBase.COMMON_VIDEO_BIT_RATE;
//            int bitrateLimits = VideoRecordingBase.COMMON_VIDEO_BIT_RATE;
//            int fps = VideoRecordingBase.VIDEO_FRAME_RATE;
//            switch (videoQuality) {
//                case VideoRecordingBase.HIGHT_VIDEO_QUALITY:
//                    bitrate = VideoRecordingBase.COMMON_VIDEO_BIT_RATE;
//                    bitrateLimits = VideoRecordingBase.COMMON_VIDEO_BIT_RATE;
//                    fps = VideoRecordingBase.VIDEO_FRAME_RATE;
//                    break;
//                case VideoRecordingBase.MIDDLE_VIDEO_QUALITY:
//                    bitrate = VideoRecordingBase.MIDDLE_VIDEO_BIT_RATE;
//                    bitrateLimits = VideoRecordingBase.MIDDLE_VIDEO_BIT_RATE;
//                    fps = VideoRecordingBase.MIDDLE_VIDEO_FRAME_RATE;
//                    break;
//                case VideoRecordingBase.LOW_VIDEO_QUALITY:
//                    showUserTip = true;
//                    bitrate = VideoRecordingBase.LOW_VIDEO_BIT_RATE;
//                    bitrateLimits = VideoRecordingBase.LOW_VIDEO_BIT_RATE;
//                    fps = VideoRecordingBase.LOW_VIDEO_FRAME_RATE;
//                    break;
//                case VideoRecordingBase.INVLAID_QUALITY:
//                    invalidFlag = true;
//                    break;
//                default:
//                    break;
//            }
//            if (invalidFlag) {
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        recordStop();
////                        load_text_tip.setText(getResources().getString(R.string.publish_timeout_tip));
////                        connect_tip_layout.setVisibility(View.VISIBLE);
//                        rbStart.setVisibility(View.VISIBLE);
////                        mCompleteBtn.setVisibility(View.GONE);
//                        Toast.makeText(VideoRecorderActivity.this, "由于当前网络环境过差，无法支持视频直播。请切换至其他网络或改善所处网络环境后重新开播！", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            } else {
//                Log.i("problem", "由于当前网络环境较差，已切换至流畅模式。如需使用高清模式，请改善所处网络环境后重新开播！[" + (int) (bitrate / 1024) + "Kbps, " + fps + "]");
//                if (showUserTip) {
//                    mHandler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            String text = "由于当前网络环境较差，已切换至流畅模式。如需使用高清模式，请改善所处网络环境后重新开播！";
//                            new AlertDialog.Builder(VideoRecorderActivity.this).setMessage(text)
//                                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int arg1) {
//                                            if (null != dialog) {
//                                                dialog.dismiss();
//                                                dialog = null;
//                                            }
//                                        }
//                                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int id) {
//                                    if (null != dialog) {
//                                        dialog.dismiss();
//                                        dialog = null;
//                                    }
//                                }
//                            }).show();
//                        }
//                    });
//                }
//                previewScheduler.adaptiveVideoQuality(bitrateLimits, bitrate, fps);
//            }
//        }
//
//        @Override
//        public void hotAdaptiveVideoQuality(int maxBitrate, int avgBitrate, int fps) {
//            previewScheduler.hotConfigQuality(maxBitrate * 1000, avgBitrate * 1000, fps);
//
//            Log.d("adaptiveVideoQuality", " maxBitrate " + maxBitrate + " fps " + fps);
//        }
//
//        @Override
//        public void statisticsBitrateCallback(int sendBitrate, int compressedBitrate) {
//        }
//    };
//
//    public void recordStop() {
//        isRecording = false;
//        isRecordedOver = true;
//        recordingStudio.stopRecording();
//    }
//
//    private void completeRecord() {
//        showProgress();
//        recordStop();
//        //TODO 怎么知道处理完了
//        mHandler.postDelayed(()->{
//            String out = VideoSDK.getVideoAlbum().append(System.currentTimeMillis()).append(".mp4").toString();
//            StringBuilder builder = new StringBuilder("ffmpeg -i ")
//                    .append(path)
//                    .append(" -c copy ")
//                    .append(out);
//            goEdit(FFUtils.run(builder.toString())==0?out:path);
//        },1000);
//
//    }
//
//    @SuppressLint("InvalidWakeLockTag")
//    private void preProcess() {
//        // 保持屏幕长亮
//        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.FULL_WAKE_LOCK,
//                "RecordActivity");
//        wakeLock.acquire();
//    }
//
//
//    private void findView() {
//        RelativeLayout rlRoot=findViewById(R.id.rlRoot);
//        surfaceView = new ChangbaRecordingPreviewView(this);
//        rlRoot.addView(surfaceView,0);
////        surfaceView = findViewById(R.id.fsSurface);
//        Point size = new Point();
//        getWindowManager().getDefaultDisplay().getSize(size);
//        ViewGroup.LayoutParams params = surfaceView.getLayoutParams();
//        params.height = size.y;
//        params.width = size.x;
//        rbStart =  this.findViewById(R.id.rbStart);
//        tvHint = findViewById(R.id.tvHint);
//        imgBack = findViewById(R.id.imgBack);
//        imgAlbum = findViewById(R.id.imgAlbum);
//
//        tvTimeLabel = findViewById(R.id.timelabel);
//
//        //Volume And PitchShift
//        setClickListeners();
//    }
//
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        if (wakeLock != null)
//            wakeLock.release();
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        // 监测耳机的拔出或者插入操作
//        if (wakeLock != null)
//            wakeLock.acquire();
//    }
//
//    private Handler mHandler = new Handler(msg->{
//        switch (msg.what){
//            case PlayerService.UPDATE_PLAY_VOICE_PROGRESS:
////            case  HANDLER_RECORD:
//                //拍摄视频的handler
//                if (!isRecordedOver) {
//                    long duration = Math.max(msg.arg1,0);//System.currentTimeMillis()-startTime;
//                    rbStart.setProgress(duration);
//                    if(VideoSDK.isShowTime)
//                        tvTimeLabel.setText(String.format("正在录制 %5.2f",duration/1000f));
////                    mHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 30);
//                }
//                break;
//        }
//        return false;
//    }) ;
//
//    private void checkCamera(){
//        List<Camera.Size> l = videoCamera.getCamera().getParameters().getSupportedPreviewSizes();
//        StringBuilder builder = new StringBuilder(" params is:");
//        for(Camera.Size size:l){
//            builder.append("\n w:").append(size.width).append(" h:").append(size.height);
//        }
//        Log.d("blensmile",builder.toString());
//    }
//
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode,resultCode,data);
//        if(resultCode == RESULT_OK && requestCode == REQUEST_KEY && data != null){
//            Intent intent = new Intent();
//            intent.putExtra("video", data.getStringExtra("videoPath"));
//            intent.putExtra("cover",data.getStringExtra("cover"));
//            setResult(RESULT_OK, intent);
//            finish();
//        }else if(resultCode == RESULT_OK && requestCode == CHOOSE_VIDEO && data!=null){
//            //去编辑
//            Log.d("blen",data.toString());
//            //data is like this: dat=content://com.android.providers.media.documents/document/video:76893 flg=0x1
//            // 判断有效性
//            Uri uri = data.getData();
//            String mVideoPath = uri.toString();
//            if (mVideoPath.startsWith("content://")) {
//                mVideoPath = FileUtils.getPathByUri4kitkat(this, uri);
//            }else if(mVideoPath.startsWith("file://")){
//                mVideoPath = mVideoPath.substring(7);
//            }
//            goEdit(mVideoPath);
//        }else {
//            initMediaRecorderState();
//        }
//    }
//
//    private void goEdit(String path){
//        hideProgress();
//        Intent intent = new Intent(this, VideoEditActivity.class);
//        intent.putExtra("path", path);
//        Log.d("blensmile","path is: "+path);
//        startActivityForResult(intent, REQUEST_KEY);
//    }
//
//
//    public void setClickListeners() {
//        imgBack.setOnClickListener(view->{
//            onBackPressed();
//        });
//        imgAlbum.setOnClickListener(view->{
//            Intent intent = new Intent();
//            intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
//            intent.setAction(Intent.ACTION_GET_CONTENT);
//            startActivityForResult(intent, CHOOSE_VIDEO);
//        });
//        rbStart.setRange(VideoSDK.VIDEO_MIN_LENGTH,VideoSDK.VIDEO_MAX_LENGTH);
//
//        rbStart.setOnGestureListener(new RecordedButton.OnGestureListener() {
//            @Override
//            public void onLongClick() {
//                //长按录像
//                isRecordedOver = false;
////                mMediaRecorder.startRecord();
//                rbStart.setSplit();
////                mHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 50);
//                isVideoData = true;
//                if(VideoSDK.isShowTime)
//                    tvTimeLabel.setVisibility(View.VISIBLE);
//                tvHint.setVisibility(View.GONE);
//                startRecord();
//            }
//            @Override
//            public void onClick() {
////                if(!isVideoData && isTakingPhoto) {
////                    //点击拍照
////                    showProgress("正在抓取屏幕, 请保持静止");
////                    mMediaRecorder.startRecord();
////                    myHandler.sendEmptyMessageDelayed(HANDLER_CAMERA_PHOTO, 30);
////                }
//            }
//            @Override
//            public void onLift() {
////                if(isSlotable) {
////                    isRecordedOver = true;
////                    mMediaRecorder.stopRecord();
////                    changeButton(mMediaObject.getMediaParts().size() > 0);
////                }else {
//                    onOver();
////                }
//            }
//
//            @Override
//            public void onOver() {
//                //判断时长
//                long duration=System.currentTimeMillis()-startTime;
//                Log.d("blensmile","duration is:"+duration+" "+tvTimeLabel.getText().toString());
//                if(duration < VideoSDK.VIDEO_MIN_LENGTH+400){
//                    recordStop();
//                    Toast.makeText(VideoRecorderActivity.this,"录屏时间太短",Toast.LENGTH_SHORT).show();
//                    initMediaRecorderState();
//                }else {
//                    rbStart.closeButton();
//                    completeRecord();
//                }
//            }
//
//            @Override
//            public void onMove() {
//
//            }
//        });
//
//
//
////        img_switch_camera.setOnClickListener((view)->{
////            previewScheduler.switchCameraFacing();
////        });
////        mMoreBtn.setOnClickListener((view)->{
////            if (!isUseHWEncoder) {
////                isUseHWEncoder = true;
////                Toast.makeText(VideoRecorderActivity.this, "已经切换为硬件编码", Toast.LENGTH_LONG).show();
////            } else {
////                isUseHWEncoder = false;
////                Toast.makeText(VideoRecorderActivity.this, "已经切换为软件编码", Toast.LENGTH_LONG).show();
////            }
////
////        });
//
//    }
//
//    private void initMediaRecorderState(){
//        if(VideoSDK.isShowTime)
//            tvTimeLabel.setVisibility(View.INVISIBLE);
//        rbStart.setVisibility(View.VISIBLE);
//        rbStart.setProgress(0);
//        rbStart.cleanSplit();
//        tvHint.setVisibility(View.VISIBLE);
//        imgAlbum.setVisibility(View.VISIBLE);
//        imgBack.setVisibility(View.VISIBLE);
//    }

}